#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <R.h>

int DMC(double *z, double *v,double *aU, double *aL,
          double *gamma, double *alpha, double *tau,
          double *s, double *h, double *resp, double *rt,
          double *n, double *maxiter,
          int *rangeLow, int *rangeHigh, double *randomTable)
{
  double rhs,x,randNum,currV,time;
  int N,i,j,iter,Maxiter,blah;
  
  N=(int) *n;
  Maxiter =(int) *maxiter;
  GetRNGstate();
  rhs=sqrt(*h)*(*s);
  
  double timeVaryingInput[Maxiter];
  for (j=0;j<Maxiter;j++) {
    time=(double) (j*(*h) + (*h));
    timeVaryingInput[j]=(*gamma)*exp(-time/(*tau))*pow(((time*exp(1))/(((*alpha)-1)*(*tau))),((*alpha)-1))*((((*alpha)-1)/time)-(1/(*tau)));
  }
  
  
  for (i=0;i<N;i++) {
    x=z[i];
    
    iter=0;
    resp[i]=(double) -1.0 ;
    do 
    {
      iter = iter+1;
      
      currV = (*v) + timeVaryingInput[(iter-1)];
      
      randNum = rand()/(1.0 + RAND_MAX);
      blah = (*rangeHigh) - (*rangeLow) + 1;
      blah = (randNum * blah) + (*rangeLow);
      randNum = randomTable[blah];
      
      x = x + (currV*(*h)) + (rhs*randNum);
      
      if (x>=*aU) {
        resp[i]=(double) 1.0 ; 
        break ;
      }
      if (x<=*aL) {
        resp[i]=(double) 2.0 ; 
        break ;
      }
    } while (iter<Maxiter) ; 
    rt[i]=(((double) iter)*(*h) - (*h)/((double) 2.0));
  }
  PutRNGstate();
}

